<template>
  <div class="page-container">
    <!--表格内容栏-->
    <ac-table
      ref="dataTable"
      pkName="id"
      :filters="filters"
      :filterFields="filterFields"
      :columns="columns"
      @handleTableOperator="handleTableOperator"
      @handleCellOperator="handleCellOperator"
    ></ac-table>

    <!--新增/编辑/查看界面-->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-form
        ref="dataForm"
        label-width="100px"
        label-position="right"
        :model="formData"
        :disabled="!dialogEdit"
        :rules="rules"
        :hide-required-asterisk="!dialogEdit"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="序名" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="前缀" prop="prefix">
              <template #label>
                <el-tooltip>
                  <template #content>
                    <p>{}大括号为需要解释的内容，可用参数：</p>
                    <p>yyyy：年份，4位</p>
                    <p>yy：年份，2位</p>
                    <p>MM：月份，2位</p>
                    <p>dd：日期，2位</p>
                    <p>HH：小时，2位</p>
                    <p>mm：分钟，2位</p>
                    <p>ss：秒钟，2位</p>
                    <p>month：月份，2位</p>
                    <p>day：日期，2位</p>
                    <p>hour：小时，2位</p>
                    <p>minute：分钟，2位</p>
                    <p>second：秒钟，2位</p>
                  </template>
                  <div>
                    <span style="margin-right: 5px">前缀</span>
                    <ac-icon iconId="018dca8ec9890493be26" />
                  </div>
                </el-tooltip>
              </template>
              <el-input v-model="formData.prefix"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="后缀" prop="suffix">
              <el-input v-model="formData.suffix"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="长度" prop="totalBit">
              <el-input v-model="formData.totalBit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="当前前缀" prop="curPrefix">
              <el-input v-model="formData.curPrefix"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="当前值" prop="currNumber">
              <el-input v-model="formData.currNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="更新时间" prop="updateTime">
              <ac-datetime v-model="formData.updateTime" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="创建时间" prop="createTime">
              <ac-datetime v-model="formData.createTime" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button
          v-if="!dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="fileVisible"
      width="500px"
      title="导入"
      :append-to-body="true"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-upload
        action=""
        :http-request="handleImport"
        :show-file-list=false
        accept=".dat"
      >
        <el-button :loading="fileLoading" type="primary">数据导入</el-button>
        <template #tip><div class="el-upload__tip">只能上传.dat文件</div></template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            size="default"
            @click="fileVisible=false"
            type="info"
          >取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import api from '@/http/api'

const filters = ref({
  name: ''
});

const filterFields = ref([
  {prop: "name", label: "序名"}
]);

const columns = ref([
  {prop: "name", label: "序名", minWidth: 110, click: true},
  {prop: "prefix", label: "前缀", minWidth: 120},
  {prop: "suffix", label: "后缀", width: 80},
  {prop: "totalBit", label: "长度", width: 80, type: 'number'},
  {prop: "curPrefix", label: "当前前缀", minWidth: 120},
  {prop: "currNumber", label: "当前序号", width: 110, type: 'number'},
  {prop: "updateTime", label: "更新时间", width: 160, type: "datetime"}
]);

const rules = ref({
  name: [
    {required: true, message: '请输入序名', trigger: 'blur'},
    {max: 50, message: '长度必须小于等于 50 个字符！', trigger: 'blur'}
  ],
  curPrefix: [
    {max: 20, message: '长度必须小于等于 20 个字符！', trigger: 'blur'}
  ],
  prefix: [
    {required: true, message: '请输入前缀', trigger: 'blur'},
    {max: 20, message: '长度必须小于等于 20 个字符！', trigger: 'blur'}
  ],
  suffix: [
    {max: 20, message: '长度必须小于等于 20 个字符！', trigger: 'blur'}
  ],
  totalBit: [
    {required: true, message: '请输入长度', trigger: 'blur'}
  ],
});

const dataForm = ref();
const formData = ref({});

const dialogTitle = ref('');
const dialogVisible = ref(false);
const dialogEdit = ref(true);
const editLoading = ref(false);
const dataTable = ref();

const fileVisible = ref(false);
const fileLoading = ref(false);

const handleImport = (file) => {
  api.uploadFile('/system/sequence/importData', {'file': file.file}).then((res) => {
    ElMessage.success(res.message);
    fileVisible.value = false;
    dataTable.value.findPage();
  });
};

const handleCellOperator = (property, value, row) => {
  formData.value = Object.assign({}, row);
  dialogVisible.value = true;
  dialogEdit.value = false;
  dialogTitle.value = "查看";

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleTableOperator = (button, row) => {
  if (button.buttonType === 'edit') {
    formData.value = Object.assign({}, row, {button: button});
    dialogVisible.value = true;
    dialogEdit.value = true;
    dialogTitle.value = button.name;
  } else if (button.buttonType === 'exportData') {
    const data = row.map(item => item.id);
    api.downloadFile('/system/sequence/exportData', {ids: data}).then(res => api.saveFileLocal(res));
  } else if (button.buttonType === 'importData') {
    fileVisible.value = true;
  } else {
    formData.value = {button: button};
    dialogVisible.value = true;
    dialogEdit.value = true;
    dialogTitle.value = button.name;
  }

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true;
        api.post(formData.value.button.dataDestUrl, formData.value).then(res => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataTable.value.findPage();
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        });
      }).catch(()=>{});
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};
</script>